﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace SqlExecuteHelper
{
    public static class TcpExtension
    {
        private static bool isConnectionSuccessful = false;
        private static ManualResetEvent timeoutObject = new ManualResetEvent(false);

        public static bool Connect(this TcpClient tcpClient, IPEndPoint remoteEndPoint, int timeoutMiliSecond)
        {
            timeoutObject.Reset();

            tcpClient.BeginConnect(remoteEndPoint.Address, remoteEndPoint.Port, (IAsyncResult asyncresult) =>
            {
                try
                {
                    isConnectionSuccessful = false;
                    TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
                    if (tcpclient.Client != null)
                    {
                        tcpclient.EndConnect(asyncresult);
                        isConnectionSuccessful = true;
                    }
                }
                catch (Exception ex)
                {
                    isConnectionSuccessful = false;
                }
                finally
                {
                    timeoutObject.Set();
                }
            }, tcpClient);

            if (timeoutObject.WaitOne(timeoutMiliSecond, false))
            {
                if (isConnectionSuccessful)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                tcpClient.Close();
                return false;
            }
        }
    }
}
